const cluster = require('cluster');
const os = require('os');

if(cluster.isMaster){
  const fork = () => {
    const worker = cluster.fork();

    let missedPing = 0;
    const timer = setInterval(() => {
      console.log('ping');
      worker.send('ping');
      missedPing++;

      if (missedPing >= 3) {
        clearInterval(timer);
        process.kill(worker.process.pid);
        console.log('发现一个僵尸进程 已清除 准备重启')
      }
    }, 300);

    worker.on('message', (msg) => {
      console.log('pong');
      if(msg === 'pong'){
        missedPing--;
      }
    });
  };

  for( let i=0;i</*os.cpus().length*/1;++i) {
    fork()
  }

  cluster.on('exit', () => {
    setTimeout(() => {
      fork()
    }, 3000/**←防止出现重新启动就死掉然后往复循环的情况造成大量的运算消耗*/);
  });

}else {
  require('./http');

  /** 1. 子进程由于程序错误挂掉后 会自动重启*/
  process.on('uncaughtException', (err) => {
    console.error(err);

    process.exit(1);
  });

  /** 2. 检查内存是否泄漏(或则内存使用过大) 自动重启*/
  setInterval(() => {
    console.log('process.memoryUsage().rss:',process.memoryUsage().rss);
    if (process.memoryUsage().rss > 734003200/*700M*/) {
      console.log('oom');
      process.exit(1);
    }
  }, 5000);

  /** 3.*/
  process.on('message', (str) => {
    if(str === 'ping'){
      process.send('pong');
    }
  });
}


